﻿<cfscript>

/** 
* Security Frameworks - Session Fade
*
* @displayname "public.service.session.fade" 
* @hint "Security session operation" 
* 
* @Output false
* 
* @accessors true
*/

component {
	
	property name="Storage" hint="Session 数据存储";
	
	/**
	* @hint "初始化对象"
	*/
	public function init() output=false {
		return this;
	}
	
	/**
	* @hint "用户登录"
	* 
	* @authUser "用户名"
	* @authGroup "用户所在用户组, 多个用户组使用,分割组合成字符串"
	*/
	public void function login( required string authUser, required string authGroup, struct userProps=structNew() ) output=false {
		
		var storage = getStorage();

		var userObj = {
						"uid" = arguments.authUser, 
						"gid" = arguments.authGroup, 
						"prop" = arguments.userProps
						};
		
		storage.create( serializeJSON( userObj ) );
	}
	
	/**
	* @hint "用户注销"
	*/
	public void function logout() output=false {
		
		storage.delete();
		
	}
	
	/**
	* @hint "返回认证用户"
	*/
	public string function getAutherUserID() output=false {
		
		var storage = getStorage();
		
		try {
			var userObj = deserializeJSON( storage.read() );
			
			return userObj["uid"];
		}
		catch ( any exception ) {
		}
		
		return "";
	}
	
	/**
	* @hint "返回认证用户所归属的用户组"
	*/
	public string function getAuthorizedUserGroups() output=false {
		
		var storage = getStorage();
		
		try {
			var userObj = deserializeJSON( storage.read() );
			
			return userObj["gid"];
		}
		catch ( any exception ) {
		}
		
		return "";
	}
	
	/**
	* @hint "返回认证用户所有属性"
	*/
	public struct function getUserProps() output=false {
		
		var storage = getStorage();
		
		try {
			var userObj = deserializeJSON( storage.read() );
			
			return userObj["prop"];
		}
		catch ( any exception ) {
		}
		
		return structNew();
	}
	
	/**
	* @hint "返回认证用户指定属性"
	* 
	* @propName "用户属性名"
	*/
	public string function getUserProp( required string propName ) output=false {

		var storage = getStorage();

		try {
			var userObj = deserializeJSON( storage.read() );
			
			return userObj["prop"][arguments.propName];
		}
		catch ( any exception ) {
		}
		
		return "";
	}
	
	/**
	* @hint "判断当前会话是否已授权"
	*/
	public boolean function isUserAuthorized() output=false {
		
		if ( len( getAutherUserID() ) ) {
			return true;
		}
		
		return false;
	}
	
	/**
	* @hint "判断当前会话的用户组, 是否在某个列表中"
	* 
	* @groupList "参考用户组"
	*/
	public boolean function isUserInAnyAuthorizedGroups( required string groupList ) output=false {
		
		var userGroups = listToArray( getAuthorizedUserGroups(), ", " );
		var targetGroups = arguments.groupList;
		
		for ( var currentGroup in userGroups ) {
			if ( listFindNoCase(targetGroups, currentGroup, ", ") ) {
				return true;
			}
		}
		
		return false;
	}
	
}

</cfscript>